package com.starrin.tennisfinder.scheduler;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.starrin.tennisfinder.extractors.ExtractorSalk;
import com.starrin.tennisfinder.model.VenueAvailabilityDataHolder;
import com.starrin.tennisfinder.system.Cache;
import com.starrin.tennisfinder.util.WebUtil;
import org.apache.log4j.Logger;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by larsstarrin on 07/02/14.
 */
public class RefreshTaskSalk implements Runnable {
    private static final int FORESIGHT_DAYS = 15;

    private Map<String, VenueAvailabilityDataHolder> newData = new HashMap<>();
    private Cache cache = Cache.getInstance();
    private static final Logger logger = Logger.getLogger(RefreshTaskSalk.class);
    private String venueKey;

    public RefreshTaskSalk(String venueKey) {
        this.venueKey = venueKey;
    }

    public void run() {
        logger.info("Start refreshing availability data for " + venueKey);
        long start = System.currentTimeMillis();
        try {
            refresh();
            //Put temp data into cache
            for (Map.Entry<String, VenueAvailabilityDataHolder> entry : newData.entrySet()) {
                cache.putEntry(entry.getKey(), venueKey, entry.getValue());
            }
            logger.info("Finished refreshing availability data for " + venueKey + " in " +  (System.currentTimeMillis() - start) / 1000 + " seconds");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void refresh() {
        try {
            WebClient webClient = new WebClient();
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setJavaScriptEnabled(false);

            Calendar today = new GregorianCalendar(new Locale("sv", "SE"));
            //int year = today.get(Calendar.YEAR);
            int weekOfYear = today.get(Calendar.WEEK_OF_YEAR);

            //Login
            WebRequest loginRequest = new WebRequest(new URL("http://www.matchi.se/j_spring_security_check"), HttpMethod.POST);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new NameValuePair("j_username", "lstarrin@hotmail.com"));
            params.add(new NameValuePair("j_password", "lap1nkulta"));
            params.add(new NameValuePair("sumbit", "Logga in"));
            loginRequest.setRequestParameters(params);
            webClient.getPage(loginRequest);

            for (int i = 0; i < FORESIGHT_DAYS; i++) {
                Calendar cal = new GregorianCalendar();
                cal.add(Calendar.DAY_OF_MONTH, i);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String dateStringForUrl = df.format(cal.getTime());

                SimpleDateFormat dfCache = new SimpleDateFormat("yyyyMMdd");
                String dateStringForCache = dfCache.format(cal.getTime());

                String url = "http://www.matchi.se/facilities/salk/1?date="+ dateStringForUrl + "&sport=";
                HtmlPage page = webClient.getPage(url);
                String response = page.getWebResponse().getContentAsString();
                response = WebUtil.getReducedResponse(response, "Bana 1", "Betalda bokningar");
                if(response != null) {
                    VenueAvailabilityDataHolder dataHolder = new ExtractorSalk().extractVenueAvailability(response, url);
                    newData.put(dateStringForCache, dataHolder);
                }
            }
        } catch(Exception e) {
             logger.error("Failed fetching data..", e);
        }
    }
}